<template>
  <div class="app-container">
    <BankView ref="dialog" :bankinfo="bankCardInfo" :visible="visible" :dialog-type="'teacher'" @isDialog="isDialog"/>
    <div class="inputBox">
      <el-input v-model="search.number" class="input" placeholder="请输入讲师编号查询" />
      <el-input v-model="search.name" class="input" placeholder="请输入姓名查询" />
      <!-- <el-input v-model="search.province" class="input" placeholder="请输入所在城市查询" /> -->
      <el-select v-model="search.type" class="teacherType" placeholder="请选择讲师分类">
        <el-option v-for="(item, index) in teacherList" :key="index" :label="item.type == 0?'禅修':'其他'" :value="item.type" />
      </el-select>
      <el-select v-model="search.sex" class="teacherSex" placeholder="请选择性别">
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
      <el-date-picker v-model="search.startTime" class="startDate" type="date" placeholder="选择开始日期"/>
      <el-date-picker v-model="search.endTime" class="endDate" type="date" placeholder="选择结束日期"/>
      <el-select v-model="search.status" class="teacherStatus" placeholder="请选择用户状态">
        <el-option label="停用" value="0" />
        <el-option label="启用" value="1" />
      </el-select>
      <el-button type="primary" class="ml10" @click="toSearch">查询</el-button>
      <el-button type="primary" @click="toReset">重置</el-button>
      <el-button v-show="permissionShow && permissionBoolean('新增')" type="primary" @click="editRow()">新增</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中请稍后"
      border
      fit
      highlight-current-row>
      <!-- <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.$index }}
        </template>
      </el-table-column> -->
      <el-table-column label="讲师编号">
        <template slot-scope="scope">
          {{ scope.row.number }}
        </template>
      </el-table-column>
      <el-table-column label="讲师姓名">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="讲师性别">
        <template slot-scope="scope">
          <p v-if="scope.row.sex === 1">男</p>
          <p v-else-if="scope.row.sex === 2">女</p>
        </template>
      </el-table-column>
      <el-table-column label="所在城市">
        <template slot-scope="scope">
          {{ scope.row.province }}{{ scope.row.city === '市辖区' ? '' : scope.row.city }}
        </template>
      </el-table-column>
      <el-table-column label="讲师分类">
        <template slot-scope="scope">
          {{ scope.row.type | typeFilter }}
        </template>
      </el-table-column>
      <el-table-column label="手机号码">
        <template slot-scope="scope">
          {{ scope.row.mobilePhone }}
        </template>
      </el-table-column>
      <el-table-column label="录入时间">
        <template slot-scope="scope">
          {{ scope.row.createTime | formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          {{ scope.row.status | statusFilter }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="微信头像">
        <template slot-scope="scope">
          <img :src="scope.row.imgUrl" class="img_url" alt="">
        </template>
      </el-table-column>
      <el-table-column label="微信号">
        <template slot-scope="scope">
          {{ scope.row.wechat }}
        </template>
      </el-table-column> -->
      <el-table-column align="center" prop="created_at" label="操作" width="290">
        <template slot-scope="scope">
          <el-button
            v-show="permissionShow && permissionBoolean('查看')"
            size="mini"
            type="warning"
            @click="look(scope.row.tid)">详情</el-button>
          <el-button
            v-show="permissionShow && permissionBoolean('绑卡')"
            :disabled="scope.row.bankCardInfo.id == null ? false : true"
            size="mini"
            type="success"
            @click="bind(scope.row.tid, scope.$index)">{{ scope.row.bankCardInfo.id ? '已绑' : '绑卡' }}</el-button>
          <el-button
            v-show="permissionShow && permissionBoolean('编辑')"
            :disabled="scope.row.status == 1"
            size="mini"
            type="primary"
            @click="editRow(scope.$index)">编辑</el-button>
          <el-button
            v-show="permissionShow && permissionBoolean('启用')"
            :type="scope.row.status == 0 ? 'success' : 'danger'"
            size="mini"
            @click="changeStatus(scope.row.tid, scope.row.status)">{{ scope.row.status == 0 ? "启用" : "禁用" }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />
  </div>
</template>

<script>
import { getTeacherList, edit, getTeacherDetail, teacherUpdateStatus } from '@/api/teacher'
import Pagination from '@/components/Pagination'
import { Message } from 'element-ui'
import { GetQiniuToken } from '@/utils/qiniuUpload.js'
import BankView from '@/components/Dialog/BankView'
import { provinceAndCityData, regionData, CodeToText, TextToCode } from 'element-china-area-data'
import { getLocalUid, setLocalUid, getLocalId, setLocalId } from '@/utils/uid'
import { getPermission } from '@/api/permission'

let url = ''
const info = { isEdit: false }

export default {
  components: { Pagination, BankView },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: '停用',
        1: '启用'
      }
      return statusMap[status]
    },
    typeFilter(status) {
      const statusMap = {
        0: '禅修',
        1: '其他'
      }
      return statusMap[status]
    },
    typeCode(item) {
      if (item === '110100' || !item) {
        return ''
      } else {
        return CodeToText[item]
      }
    }
  },
  data() {
    return {
      visible: false,
      bankCardInfo: {
        name: '',
        idCard: '',
        phone: '',
        bankCard: ''
      },
      labeWidth: '120px',
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10
      },
      search: {
        number: '',
        name: '',
        province: '',
        type: '',
        sex: '',
        startTime: '',
        endTime: ''
      },
      isShowDel: false,
      dialogFormVisible: false,
      temp: {
        status: ''
      },
      courseTypeId: null,
      dialog: false,
      course: {
        name: '',
        introduce: '',
        price: '',
        imgUrl: ''
      },
      typeDialogTitle: '新增',
      fileList: [],
      imgSrc: '',
      actionUrl: 'https://upload-z2.qiniup.com',
      isEdit: false,
      uploadData: {
        key: '',
        token: ''
      },
      teacherList: [],
      permissionShow: false, // 权限数据未到达之前按钮隐藏
      permissionList: [] // 权限数据列表
    }
  },
  computed: {
    permissionBoolean() {
      return function(str) {
        const arr = []
        for (let i = 0; i < this.permissionList.length; i++) {
          arr.push(this.permissionList[i].name)
        }
        const index = arr.indexOf(str)
        // console.log(arr)
        // console.log('index', index, str)
        if (index !== -1) {
          return true
        } else {
          return false
        }
      }
    }
  },
  watch: {
    'permissionList'(newVal) {
      this.permissionList = newVal
      this.permissionShow = true
    }
  },
  created() {
    this.fetchData()
    this.getPermissonFn()
    this.getPermissonFn() // 接口 - 权限列表
  },
  mounted() {
    this.uploadData.token = GetQiniuToken().uploadToken
  },
  methods: {
    // 权限数据的获取
    getPermissonFn() {
      const id = getLocalId()
      const uid = getLocalUid()
      const data = { uid }
      getPermission(id, data).then(res => {
        console.log('权限结果', res)
        if (res.code === '200') {
          this.permissionList = res.data
          // console.log('权限名称：', this.getPermissionName(this.permissionList))
        } else {
          Message.error(res.message + '-' + res.data)
        }
      })
    },
    getPermissionName(arr) {
      const myArr = []
      for (let i = 0; i < arr.length; i++) {
        myArr.push(arr[i].name)
      }
      return myArr
    },
    bind(tid, index) {
      // console.log(this.bankCardInfo)
      // console.log('list:', this.list)
      this.bankCardInfo.name = this.list[index].name
      this.bankCardInfo.idCard = this.list[index].idNo
      this.bankCardInfo.phone = this.list[index].mobilePhone
      // this.bankCardInfo
      this.$refs.dialog.getMsg(tid)
      this.visible = true
    },
    isDialog(a) {
      this.visible = false
      this.fetchData()
    },
    // 点击启用或者禁用改变状态
    changeStatus(tid, status) {
      let str = ''
      let newStatus = 0
      str = status === 0 ? '是否启用？' : '是否禁用？'
      newStatus = status === 0 ? 1 : 0
      const data = {
        tid, status: newStatus
      }
      this.$confirm('确认要删除该咨询？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        message: str,
        type: 'warning'
      }).then(() => {
        teacherUpdateStatus(data).then(res => {
          console.log('停用启用:', res)
          if (Number(res.code) === 200) {
            this.fetchData()
          }
        })
      }).catch(() => {
      })
    },
    // 重置
    toReset() {
      this.search.number = ''
      this.search.name = ''
      this.search.province = ''
      this.search.type = ''
      this.search.sex = ''
      this.search.startTime = ''
      this.search.endTime = ''
      this.search.status = ''
      this.search.pageNum = 0
      this.search.pageSize = 10
    },
    // 查询
    toSearch() {
      if (!this.search.startTime) this.search.startTime = ''
      if (!this.search.endTime) this.search.endTime = ''
      if (this.search.startTime) this.search.startTime = new Date(this.search.startTime).getTime();
      if (this.search.endTime) this.search.endTime = new Date(this.search.endTime).getTime();
      // this.search.endTime = new Date(this.search.endTime).getTime();
      // console.log(this.search)
      this.listLoading = true
      const newData = this.objectCon(this.listQuery, this.search)
      console.log('讲师列表搜索：', newData)
      getTeacherList(newData).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    fetchData() {
      const newData = this.objectCon(this.listQuery, this.search)
      this.listLoading = true
      getTeacherList(newData).then(response => {
        console.log(response.data.list)
        // this.list = response.data.list
        // 筛选出选择讲师分类的类型 type
        const arr = new Map();
        this.teacherList = response.data.list.filter((a) => !arr.has(a.type) && arr.set(a.type, 1))
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    del(pid) {
      this.$confirm('确认要删除该咨询？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      }).catch(() => {
      })
    },
    look(tid) {
      info.isEdit = false
      localStorage.setItem('isEdit', JSON.stringify(info))
      this.$store.dispatch('tAddlistIsEdit', false)
      const query = { isEdit: false, tid }
      this.$router.push({
        path: '/teacherAdd',
        query
      })
    },
    edit(tid) {
      const query = { isEdit: true, id: tid }
      this.$router.push({
        path: '/vocational/courseAdd',
        query
      })
    },
    deleteCourse(courseId, id) {
      this.$confirm('确认要移除该课程？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          courseId: courseId,
          courseTypeId: id
        }
      }).catch(() => {
      })
    },
    addCourse(courseTypeId) {
      this.$data.courseTypeId = courseTypeId
      this.$data.dialogFormVisible = true
    },
    getValue(value) {
      this.$data.temp.status = value
    },
    getEnable(value) {
      this.$data.course.isEnable = value
    },
    getChildren(value) {
      this.$data.course.courseList = value
    },
    editRow(id) {
      info.isEdit = true
      localStorage.setItem('isEdit', JSON.stringify(info))
      this.$store.dispatch('tAddlistIsEdit', true)
      const that = this;
      if (id || Number(id) === 0) {
        this.$router.push({
          path: '/teacherAdd',
          query: Object.assign(that.$data.list[id], {
            isOrder: false,
            isEdit: true
          })
        })
      } else {
        this.$router.push({
          path: '/teacherAdd'
        })
      }
    },
    handleRemove(file, fileList) {},
    handlePreview(file) {},
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`).then(() => {
        this.imgSrc = null
        url = ''
      })
    },
    beforeAvatarUpload(file) {
      // var observable = qiniu.upload(file, key, token, putExtra, config)
      const isPNG = file.type === 'image/png'
      const isJPEG = file.type === 'image/jpeg'
      const isJPG = file.type === 'image/jpg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isPNG && !isJPEG && !isJPG) {
        this.$message.error('上传头像图片只能是 jpg、png、jpeg 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      this.uploadData.key = `upload_pic_${new Date().getTime()}_${file.name}`
    },
    change(file, fileList) {
      this.imgSrc = fileList.url
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-icon-remove {
    margin-left: 10px;
  }
  .img_url {
    width: 110px;
    height: 110px;
  }
  .inputBox{
    div{ margin-bottom: 10px;}
    .input:nth-of-type(1){ width: 160px;}
    .input:nth-of-type(2){ width: 140px;}
    .input:nth-of-type(3){ width: 160px;}
    .teacherType { width: 150px;}
    .teacherSex { width: 120px;}
    .startDate { width: 150px;}
    .endDate { width: 150px;}
    .teacherStatus { width: 150px;}
}
</style>
